package cn.neusoft.service.impl;


import cn.neusoft.mapper.EmpMapper;
import cn.neusoft.page.PageBean;
import cn.neusoft.pojo.Emp;
import cn.neusoft.query.EmpQuery;
import cn.neusoft.service.IEmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EmpService implements IEmpService {

    @Autowired
    EmpMapper empMapper;

    @Transactional
    //添加方法
    public String add(Emp emp){
        if (emp==null || emp.getEname()==null || "".equals(emp.getEname())){
            return "fail";
        }
        int add = empMapper.add(emp);
        return add>0?"success":"fail";
    }

    @Transactional
    //修改方法
    public String update(Emp emp){
        if (emp==null || emp.getEmpno()==null || emp.getEname()==null || "".equals(emp.getEname())){
            return "fail";
        }
        int update = empMapper.update(emp);
        return update>0?"success":"fail";
    }

    @Transactional
    //删除方法
    public String del(Integer empno){
        if (empno==null){
            return "fail";
        }
        int del = empMapper.del(empno);
        return del>0?"success":"fail";
    }

    //通过主键查询
    public Emp getById(Integer empno){
        if (empno==null){
            return null;
        }
       return empMapper.getById(empno);
    }
    //查询所有
    public List<Emp> getAll(){
        return empMapper.getAll();
    }

    @Override
    public PageBean<Emp> getByPage(EmpQuery empQuery) {

        if (empQuery==null){
            empQuery = new EmpQuery();
        }

        if (empQuery.getCurrentPage()<1){
            empQuery.setCurrentPage(1);
        }

        if (empQuery.getPageSize()<5){
            empQuery.setPageSize(5);
        }

        PageBean<Emp> pageBean = new PageBean<>();

        //查询总记录
        int count = empMapper.getCount(empQuery);
        pageBean.setTotalRows(count);

        //计算总页数
        int totalPages = count%empQuery.getPageSize()==0?count/empQuery.getPageSize():count/empQuery.getPageSize()+1;
        pageBean.setTotalPages(totalPages);

        //查询当前页集合
        List<Emp> data = empMapper.getByPage(empQuery);
        pageBean.setData(data);

        return pageBean;
    }

}
